﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace KINLO.UI.Main.MES
{
    public class CFGLoader
    {
        #region 
        static string directory = "config";
        static CFGLoader()
        {
            if (!Directory.Exists(directory))
            {
                var r = Directory.CreateDirectory(directory);
            }
        }
        static object lockSave = new object();
        public static bool Save(object obj)
        {
            try
            {
                lock (lockSave)
                {
                    var jsonStr = JsonConvert.SerializeObject(obj, Formatting.Indented);
                    File.WriteAllText($"{directory}\\{obj.GetType().Name}.json", jsonStr, Encoding.UTF8);
                    return true;
                }

            }
            catch (Exception ex)
            {
                return false;
            }
        }
        public static object lockLoad=new object();
        public static T Load<T>()
        {
            try
            {
                lock(lockLoad)
                {
                    var filePath = $"{directory}\\{typeof(T).Name}.json";

                    if (!File.Exists(filePath))
                    {
                        // 如果文件不存在，根据该类创建对应格式的空的 JSON 对象，并保存为文件
                        var emptyObject = JsonConvert.SerializeObject(Activator.CreateInstance<T>(), Formatting.Indented);
                        File.WriteAllText(filePath, emptyObject, Encoding.UTF8);
                    }

                    var str = File.ReadAllText(filePath, Encoding.UTF8);
                    var r = JsonConvert.DeserializeObject<T>(str);
                    return r;
                }
             
            }
            catch (Exception ex)
            {
                // 发生异常时返回一个新的实例
                return Activator.CreateInstance<T>();
            }
        }
        //public static T Load<T>()
        //{
        //    try
        //    {
        //        var str = File.ReadAllText($"{directory}\\{typeof(T).Name}.json", Encoding.UTF8);
        //        var r = JsonConvert.DeserializeObject<T>(str);
        //        return r;
        //    }
        //    catch (Exception ex)
        //    {
        //        return Activator.CreateInstance<T>();
        //    }
        //}
        #endregion

    }
}
